package udpchatdemo01;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

/**
 * 模拟控制台发送消息，接收端展示接收消息,发送端只发送，接收端只接收
 *
 * 发送端
 */
public class UdpSenderDemo01 {
    public static void main(String[] args) throws IOException {
        // 创建发送端 socket
        DatagramSocket socket = new DatagramSocket(8888);

        // 准备打包发送的数据，监听控制台输入
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        // 读取控制台的数据到包裹中,直到读取到bye,结束控制台输入
        while(true) {
            String s = reader.readLine();
            byte[] data = s.getBytes();
            DatagramPacket packet = new DatagramPacket(data, 0, data.length, new InetSocketAddress("localhost", 6666));

            // 发送消息包裹
            socket.send(packet);

            if (s.equals("bye")){
                break;
            }
        }
        // 关闭 socket
        socket.close();
    }
}
